import type { FormInstance } from 'element-plus'
import type { ValuesType, SelectAddressState } from '../data/typings'
import { defineComponent, ref, reactive } from 'vue'
import { useStore } from 'vuex'
import { uniqWith } from 'lodash'
import {
  ElRow,
  ElCol,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElLink,
  ElMessage
} from 'element-plus'
import AliIcon from '~/components/AliIocn'
import MapView from '../../assetManagement/components/map/MapViewLampPost'
import useVuexGetters from '~/hooks/useVuexGetters'
import { GUTTER } from '~/utils/const'
import styles from '../index.module.scss'
import SetLamppostScope from '../distribution/SetLamppostScope'
import BaseStation from '../../assetManagement/components/assetHomeComponents/BaseStation'

export default defineComponent({
  name: 'MapLocation',
  props: ['detail', 'type'],
  emits: ['setHandleChange'],
  setup(props, { expose, emit }) {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>()
    const mapViewRef = ref() // 地图
    const selectAddressRef = ref<string>() // 搜索地址
    const formValues = reactive<ValuesType>(
      props?.detail
        ? {
            id: props.detail?.id, // 行id
            address: props.detail?.address, // 显示的地址
            addressCoordinates: props.detail?.lat && `${props.detail?.lat},${props.detail?.lon}`, // 显示坐标
            regionName: props.detail?.regionName, // 所属地区
            lon: props.detail?.lon, // 经度
            lat: props.detail?.lat // 纬度
          }
        : {}
    )

    const state = reactive<SelectAddressState>({
      marker: {
        lng: formValues.lon ?? undefined,
        lat: formValues.lat ?? undefined
      },
      satelliteChangingOverShow: false,
      setLamppostScopeShow: false
    })
    const userState = useVuexGetters('user', ['userAddressInfo'])

    // 故障地点搜索
    const remoteMethod = (value: string) => {
      if (value !== '') {
        state.loading = true
        // clearTimeout(timer)
        // timer = setTimeout(() => {
        mapViewRef.value.aMapRef.plugin(['AMap.PlaceSearch'], () => {
          const plcceSearch = new mapViewRef.value.aMapRef.PlaceSearch({
            pageIndex: 1, // 页码
            pageSize: 20, // 单页显示结果条数
            // city: '武汉'
            city: userState.userAddressInfo.value.city,
            citylimit: false
          })
          plcceSearch.search(value, (status: string, result: Record<string, any>) => {
            // 搜到的数据
            state.loading = false
            state.defectAddressSelectList =
              status === 'complete' && result.info === 'OK'
                ? uniqWith(
                    result.poiList.pois,
                    (item: { name: string }, nextItem: { name: string }) =>
                      item.name === nextItem.name
                  )
                : []
          })
        })
        // }, 200)
      }
    }

    // 选择后标点
    const addressChange = (value: string) => {
      state.defectAddressSelectList?.forEach((item) => {
        if (item.name === value) {
          formValues.addressCoordinates = item.location.lng
            ? `${item.location.lng},${item.location.lat}`
            : ''
          state.marker = item.location ? { lng: item.location.lng, lat: item.location.lat } : {}
          const timer = setTimeout(() => {
            mapViewRef.value.setMarkersByPropsMarkers()
            clearTimeout(timer)
          }, 0)
        }
      })
    }

    // 修改经纬度回调
    const handleChangeAddressCoordinates = (value: string) => {
      selectAddressRef.value = undefined
      formValues.address = undefined
      state.marker = value?.includes(',')
        ? {
            lng: parseFloat(formValues.addressCoordinates?.split(',')[0]!),
            lat: parseFloat(formValues.addressCoordinates?.split(',')[1]!)
          }
        : undefined

      if (!state.marker) mapViewRef.value.clearCurrentMarker()
      // 只有新增的可打点一次, 此外均不可打点, 所以这段暂注释掉
      // const addressArr = formValues.addressCoordinates?.split(',') ?? []
      // const addressObj = {
      //   lnglat: {
      //     lng: addressArr[0],
      //     lat: addressArr[1]
      //   }
      // }
      // setTimeout(() => {
      //   mapViewRef.value.handleClickAMapCallback(addressObj)
      // }, 100)
    }

    // 根据经纬度回传得到的汉字地址
    const changeAddress = (address: any) => {
      formValues.address = address.defectAddress
      formValues.regionName = address.region
      formValues.addressCoordinates = address.longitude
        ? `${address.longitude},${address.latitude}`
        : ''
    }

    //  卫星地图切换
    const satelliteChangingOver = () => {
      state.satelliteChangingOverShow = !state.satelliteChangingOverShow
      mapViewRef.value.satelliteChangingOver(state.satelliteChangingOverShow)
    }

    // 设置灯杆范围
    const onSetLamppostScope = () => {
      state.setLamppostScopeShow = !state.setLamppostScopeShow
    }
    //  设置灯杆范围
    const onSetHandleChange = async (scope: string) => {
      const res = await store.dispatch('base/SetLampPostScope', { scope })
      if (res.code === 200) {
        ElMessage({ type: 'success', message: res.msg })
        mapViewRef.value.onAmbitusLamp()
        emit('setHandleChange')
      }
    }
    //  更新点位数据
    const onAmbitusLamp = () => {
      state.marker = {
        lng: props.detail?.lon,
        lat: props.detail?.lat
      }
      setTimeout(() => {
        mapViewRef.value.onAmbitusLamp()
        mapViewRef.value.handleAddAMapMarker(props.detail?.lon, props.detail?.lat)
      }, 50)
    }

    // 灯杆详情展示
    const handleChangePatternMarkerInfoView = (
      left: number,
      top: number,
      type: any,
      info: any,
      pointList: any
    ) => {
      state.patternMarkerType = type
      state.patternMarkerInfo = info
        ? {
            popoverInfo: info,
            left,
            top,
            pointList
          }
        : undefined
    }

    // 更新弹框位置
    const handleChangePatternMarkerInfoPosition = (left: number, top: number) => {
      if (!state.patternMarkerInfo) return
      state.patternMarkerInfo!.left = left
      state.patternMarkerInfo!.top = top
    }

    // 关闭配电设施 灯 灯杆弹框
    const handleCancelPatternMarkerPopover = () => {
      state.patternMarkerType = undefined
      state.patternMarkerInfo = undefined
      // mapViewRef.value.clearActiveMarkerEvent()
    }

    expose({ ruleFormRef, formValues, onAmbitusLamp })

    return () => (
      <>
        <MapView
          id={styles['map-location-lamp']}
          ref={mapViewRef}
          clickon
          marker={state.marker}
          onChangeAddress={changeAddress}
          onChangePatterMarkerInfoView={handleChangePatternMarkerInfoView}
          onChangePatterMarkerInfoPosition={handleChangePatternMarkerInfoPosition}
        />
        {/* 灯杆信息弹框 */}
        {state.patternMarkerType === 'BaseStation' && (
          <BaseStation
            {...(state.patternMarkerInfo || {})}
            onCancel={handleCancelPatternMarkerPopover}
          />
        )}
        {/* 范围设置 */}
        <div
          class={{
            [styles['satellite-changing-over']]: true
          }}
          style="right: 112px;"
          onClick={onSetLamppostScope}
        >
          范围设置
        </div>
        {/* 范围设置弹框 */}
        {state.setLamppostScopeShow && (
          <SetLamppostScope
            visible={state.setLamppostScopeShow}
            onClose={onSetLamppostScope}
            onHandleChange={onSetHandleChange}
          />
        )}
        {/* 卫星地图切换 */}
        <div
          class={{
            [styles['satellite-changing-over']]: true,
            [styles['satellite-changing-over-actions']]: !state.satelliteChangingOverShow
          }}
          onClick={satelliteChangingOver}
        >
          <AliIcon type="icon-a-weixinghangtiantianwen1" />
          &nbsp;卫星
        </div>
        <ElFormItem class={styles['map-location-select-address']}>
          <ElSelect
            v-model={selectAddressRef.value}
            filterable
            suffixIcon={<AliIcon type="icon-sousuo" />}
            remote
            defaultFirstOption
            clearable
            remoteMethod={remoteMethod}
            onChange={addressChange}
            placeholder="请输入地址"
            loading={state.loading}
            // clearable
          >
            {state.defectAddressSelectList?.map((item) => (
              <ElOption
                label={item.name}
                value={item.name}
                class={styles['map-location-option-address']}
              >
                <ElLink underline={false} type="info">
                  <AliIcon type="icon-ditudingwei" />
                </ElLink>
                <section class="option-text">
                  <b>{item?.name}</b>
                  <p>{item?.address}</p>
                </section>
              </ElOption>
            ))}
          </ElSelect>
        </ElFormItem>
        <ElForm ref={ruleFormRef} model={formValues} labelWidth={90} labelPosition="right">
          <ElRow gutter={GUTTER}>
            <ElCol span={24}>
              <ElFormItem
                prop="addressCoordinates"
                label="地址坐标"
                rules={[{ required: true, message: '请输入地址坐标"xxx,xxx"', trigger: 'blur' }]}
              >
                <ElInput
                  v-model={formValues.addressCoordinates}
                  {...{ maxlength: 50 }}
                  onChange={handleChangeAddressCoordinates}
                  clearable
                />
              </ElFormItem>
            </ElCol>
            <ElCol span={24}>
              <ElFormItem
                prop="address"
                label="详细地址"
                rules={[{ required: true, message: '请输入详细地址', trigger: 'blur' }]}
              >
                <ElInput
                  readonly
                  v-model={formValues.address}
                  suffixIcon={<AliIcon type="icon-dingwei" />}
                  {...{ maxlength: 100 }}
                  placeholder="请输入 最长100字符"
                />
              </ElFormItem>
            </ElCol>
            <ElCol span={24}>
              <ElFormItem
                prop="regionName"
                label="所属地区"
                rules={[{ required: true, message: '请输入所属地区', trigger: 'blur' }]}
              >
                <ElInput
                  readonly
                  disabled
                  v-model={formValues.regionName}
                  suffixIcon={<AliIcon type="icon-dingwei" />}
                  {...{ maxlength: 100 }}
                  placeholder="请输入 最长100字符"
                />
              </ElFormItem>
            </ElCol>
          </ElRow>
        </ElForm>
      </>
    )
  }
})
